/**
 * 
 */
package com.wubo.sec.acl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.wubo.sec.acl.core.AclManager;
import com.wubo.sec.bean.UserRoleRelate;
import com.wubo.sec.filter.RoleBeforeFilter;
import com.wubo.sec.model.Role;
import com.wubo.sec.model.User;
import com.wubo.sec.service.IRoleService;
import com.wubo.sec.service.IUserService;

/**
 * @author WuBo
 * @CreateDate 2012-4-23
 */
@Component
public class UserRoleAcl extends EntityRelateAcl {
	@Resource
	private IUserService userService;
	@Resource
	private IRoleService roleService;
	
	public int getAcl(Object obj) {
		UserRoleRelate urr = (UserRoleRelate) obj;
		User user = userService.getByUsername(urr.getUsername());
		int userAcl = new UserAcl(user).getAcl();
		if(! AclManager.getInstance().hasActions(userAcl, "ACL_DEL")){
			return 0;
		}
		String[] roleCodes = urr.getRoleCodes();
		if(roleCodes == null || roleCodes.length == 0){
			return AclManager.getInstance().getAcl("ACL_RELATE");
		}
		List<Role> roles = roleService.findRunAs("where 1=1"+new RoleBeforeFilter().sift(), null);
		int match = 0;
		for(Role role : roles){
			for(String roleCode : roleCodes){
				if(role.getCode().equals(roleCode)){
					match ++;
					break;
				}
			}
		}
		if(match >= roleCodes.length){
			return AclManager.getInstance().getAcl("ACL_RELATE");
		}
		return 0;
	}
	
}
